/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var weuiAlert = require('../layer/weuialert');
var ajax = require("mlib/io/ajax");
var closest = require("mlib/dom/closest");
var Countdown = require("../plugin/util/countdown");
var validator = require("../plugin/util/validator");
var getFormData = require("../plugin/util/get-form-data");
var touch = require("mlib/evt/touch");


module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	var v = null;
	var iscding = false;
	var m_exptime = null;
	var send_mobiles = [];
	var storage_mobile = null;
	var m_cdown = null ;
    //-------------事件响应声明---------------
    var evtFuncs = {}

    //-------------子模块实例化---------------
    var initMod = function() {
      v = new validator("bindmobile-form",[
			{
				//name 字段
				name: 'mobile',
				display:"请输入你的手机号码|请输入正确的手机号码",
				// 验证条件
				rules: 'required|is_phone'
			},
            {
                //name 字段
                name: 'verifyCode',
                display:"请输入图形验证码|图形验证码不正确",
                // 验证条件
                rules: 'required|is_vcode'
            },
            {
                //name 字段
                name: 'msgcode',
                display:"请输入手机验证码|手机验证码不正确",
                // 验证条件
                rules: 'required|is_mcode'
            }
		],function(obj,evt){
			
		  if(obj.errors.length==0 && (evt!="verifyCode")){
				 var formData = getFormData(document.getElementById('bindmobile-form')); 
				if(that.isLock()) {
					return;
				}
				that.lock();             
				 ajax({// 验证通过后绑定手机号
					url: data.bindmobile+data.ocid,
					data: {
							"mobile":formData.mobile,
							"verifyCode":formData.verifyCode,
							"msgcode":formData.msgcode
						},
					method: "post",
					onSuccess: function(res) {
						that.unLock();
						if(res.error==0){
							//weuiAlert("一卡通绑定成功");
							location.href= res.url;
						}else{
							weuiAlert(res.msg);
						}
					},
					onError: function(xmlHttp) {
						 that.unLock();
					}, // 当访问出错，比如网络连接不上、解析内容失败时触发，超时也会触发
					onTimeout: function(xmlHttp) { }, // 超时触发
					onAbort: function() {} // 网络中断时触发
				 });
			 

		  }else{             

			 switch(evt){
				 case "verifyCode" :
					var isValid = true;
					 obj.errors.forEach(function(item,index){
						 if(item.name=="verifyCode"){	
							 if(item.rule=="required"){
								 weuiAlert("请输入图形验证码");
							 }
							 if(item.rule=="is_vcode"){
								 weuiAlert("图形验证码格式错误");
							 }	 
							 isValid = false;
							// if(){}
						 }
					 });
					 if(isValid){
						if(that.isLock()) {
							return;
						}
						that.lock();
						 ajax({ // 先验证图片验证码是否正确
							url: data.chkregcode,
							data: {
								"verifyCode":nodeList.vcode.value
							},
							method: "post",
							onSuccess: function(result) {
								that.unLock();
								if(result.error==0){									
									 ajax({//图片验证码验证成功后发送手机验证码								 
										url: data.sendmsg,
										data: {
												"mobile":nodeList.mobile.value,
												"type":"register"
										},
										method: "post",
										onSuccess: function(res) {
											if(res.error==0){
											   // 进行倒计时
												nodeList.sendMobile.setAttribute("disabled","disabled");
												m_cdown && m_cdown.abort();
												m_cdown = new Countdown(30, function(seconds) {
												   nodeList.sendMobile.innerText =seconds+"秒后重发"; //log the number of seconds that have passed
												}, function() {
												   nodeList.sendMobile.removeAttribute("disabled"); //log that the countdown has complete
												   nodeList.sendMobile.innerText = "发送验证码";
												});		
											}else{
												weuiAlert(res.msg);
											}
							   
										},
										onError: function(xmlHttp) {

										}
									 });
								}else{
									custFuncs.updateCode();
									weuiAlert("验证码错误");
								}

							},
							onError: function(xmlHttp) {
                                  that.unLock();
							}
						 });
						 
					 }
				 break;
				 default :
					 if(obj.errors.length){
						 weuiAlert(obj.errors[0].message);
					 }				    
			 }
             
          }
		});
        
		if(localStorage.getItem("send_mobile")){
			storage_mobile = JSON.parse(localStorage.getItem("send_mobile"));
			if(storage_mobile.length>0){
				var m_phone = storage_mobile[storage_mobile.length-1];
				nodeList.mobile.value = m_phone;
				custFuncs.canSendMobile(m_phone);
			}			 
		}
		wechat('off').init();
    };

	
    //-------------绑定事件------------------
    var bindEvents = function() {
		touch.on(nodeList.button,"tap",function(evt){			
			 v.validate();
		});
		
		touch.on(nodeList.refreshcode,"tap",function(evt){
			 custFuncs.updateCode();
		});
		
		nodeList.mobile.addEventListener("input",function(evt){
			var mobile = this.value;
			if(v.isPhone(mobile)){
				send_mobiles.push(mobile);
				localStorage.setItem("send_mobile",JSON.stringify(send_mobiles));	
                custFuncs.canSendMobile(mobile);
			}

		});
		nodeList.sendMobile.addEventListener("tap",function(evt){
			if(v.isPhone(nodeList.mobile.value)){
				if(this.disabled || iscding){
					return;
				}	
				v.validate("verifyCode");
			}else{				
				nodeList.mobile.value=='' ?	weuiAlert("请输入你的手机号码") : weuiAlert("请输入正确的手机号码");				
			}


		});
	}

    //-------------自定义函数----------------
    var custFuncs = {
         updateCode:function(){			 
			 nodeList.imgcode.src = data.imgcode + new Date().getTime();
		 },
		 canSendMobile:function(phone){
				if(that.isLock()) {
					return;
				}
				that.lock();
				 ajax({ // 先验证图片验证码是否正确
					url: "/index.php?r=moponcard/issendcode&ocid="+data.ocid,
					data: {
						"mobile":phone
					},
					method: "post",
					onSuccess: function(res) {
						that.unLock();
						if(res.error==0){
							if(res.data.status==0){
								m_cdown && m_cdown.abort();
								nodeList.sendMobile.removeAttribute("disabled");
								nodeList.sendMobile.innerText = "发送验证码";								
							}else{
								m_exptime = res.data.exptime;
								nodeList.sendMobile.setAttribute("disabled","disabled");
								
								m_cdown = new Countdown(res.data.exptime, function(seconds) {
								   m_exptime =  seconds;
								   nodeList.sendMobile.innerText =seconds+"秒后重发"; //log the number of seconds that have passed
								}, function() {		   
								   iscding = false;
								   m_exptime = 0 ;
								   if(v.isPhone(nodeList.mobile.value)){
									   nodeList.sendMobile.removeAttribute("disabled");
								   }
								   nodeList.sendMobile.innerText = "发送验证码";
								});	

							}
						}else{
							weuiAlert(res.msg);
						}
					},
					onError: function(xmlHttp) {
						  that.unLock();
					}
				 });
		 }
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;
        // 根据数据初始化模块
        // opts["render"]({ "title": data["title"] });

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);

        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();


    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};